package com.sky.aop;


import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
public class AutoAspect {

    //注解只能写在mapper层否则会报错
    @Pointcut("@annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut(){}

    @Before("autoFillPointCut()")
    public void before(JoinPoint joinPoint) {
        //1.获取当前拦截的方法上面的AutoFill注解，获取这个注解里面的枚举项，判断是新增还是修改
        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        Method method = methodSignature.getMethod();

        AutoFill autoFill = method.getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();

        Object[] args = joinPoint.getArgs();
        if(null == args || args.length == 0){
            return;
        }
        //获取参数的对象
        Object entity = args[0];

        if(OperationType.INSERT == operationType){
            //2.如果是新增，则添加四个属性
            try {
                Class clazz = entity.getClass();

                Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                setCreateTime.invoke(entity, LocalDateTime.now());

                Method setUpdateTime = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                setUpdateTime.invoke(entity, LocalDateTime.now());

                Method setCreateUser = clazz.getDeclaredMethod(AutoFillConstant.SET_CREATE_USER,Long.class);
                setCreateUser.invoke(entity, BaseContext.getCurrentId());

                Method setUpdateUser = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
                setUpdateUser.invoke(entity, BaseContext.getCurrentId());


            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }else if(OperationType.UPDATE == operationType){
            //3.如果是修改，则增强两个属性
            try {
                Class clazz = entity.getClass();

                Method setUpdateTime = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                setUpdateTime.invoke(entity, LocalDateTime.now());

                Method setUpdateUser = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
                setUpdateUser.invoke(entity, BaseContext.getCurrentId());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

}